﻿
using Bridge.Shared.Extensions;
using Bridge.Workflow;
using Bridge.Workflow.EntityFrameworkCore;
using Bridge.Workflow.WorkflowCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Volo.Abp;
using Volo.Abp.AspNetCore.MultiTenancy;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.AntiForgery;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Auditing;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.Autofac;
using Volo.Abp.Caching.StackExchangeRedis;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.MySQL;
using Volo.Abp.Http.Client.IdentityModel.Web;
using Volo.Abp.Identity;
using Volo.Abp.Identity.EntityFrameworkCore;
using Volo.Abp.Json;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement.EntityFrameworkCore;
using Volo.Abp.SettingManagement.EntityFrameworkCore;
using Volo.Abp.Timing;

namespace Bridge.WorkflowService.Host.Startup
{
    /// <summary>
    /// 
    /// </summary>
    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpAspNetCoreMvcModule),
        typeof(AbpEntityFrameworkCoreMySQLModule),
        typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        typeof(AbpPermissionManagementEntityFrameworkCoreModule),
        typeof(AbpSettingManagementEntityFrameworkCoreModule),
        //typeof(AbpIdentityHttpApiModule),
        typeof(AbpIdentityEntityFrameworkCoreModule),
        typeof(AbpIdentityApplicationModule),
        typeof(AbpAspNetCoreMultiTenancyModule),
        typeof(AbpAspNetCoreSerilogModule),
        typeof(WorkflowApplicationModule),
        typeof(WorkflowEntityFrameworkCoreModule),
        typeof(WorkflowHttpApiModule),
        typeof(AbpCachingStackExchangeRedisModule),
        typeof(AbpHttpClientIdentityModelWebModule) //传送token  SPD跨程序 OMS
    )]
    public class WorkflowWebHostModule : AbpModule
    {
        private const string DefaultCorsPolicyName = "Default";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            Configure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(WorkflowApplicationModule).Assembly, option =>
                {
                    option.TypePredicate = type => { return false; };
                    //option.UseV3UrlStyle = true;
                });
            });

            var configuration = context.Services.GetConfiguration();
        
            WorkFlowConfig._config = configuration;

              //全局更新时间返回格式
              Configure<AbpClockOptions>(options =>
            {
                options.Kind = DateTimeKind.Local;
            });
            context.Services.AddControllers().AddNewtonsoftJson();
            //Configure<MvcNewtonsoftJsonOptions>(options =>
            //{
            //    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//对类型为DateTime的生效
            //    //options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
            //    //{
            //    //    NamingStrategy = new CamelCaseNamingStrategy()
            //    //};
            //});
            Configure<AbpJsonOptions>(options =>
               options.OutputDateTimeFormat = "yyyy-MM-dd HH:mm:ss" //对类型为DateTimeOffset生效
            );


            Configure<AbpMultiTenancyOptions>(options =>
            {
                options.IsEnabled = true;
            });

            context.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = configuration["AuthServer:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience = "WorkflowService";
                options.TokenValidationParameters.ValidateIssuer = false;
            });

            Configure<AbpDbContextOptions>(options =>
            {
                options.UseMySQL();
            });

            context.Services.UseRedis(configuration);

            //Configure<AbpAuditingOptions>(options =>
            //{
            //    options.IsEnabledForGetRequests = true;
            //    options.ApplicationName = nameof(LogApplicationNameEnum.WorkflowService);
            //});

            //跨域
            context.Services.AddCors(options => options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.AllowAnyMethod()
                     .SetIsOriginAllowed(_ => true)
                     .AllowAnyHeader()
                     .AllowCredentials();
            }));

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
                options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
                options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
                options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
            });


            Configure<AbpAntiForgeryOptions>(options =>
            {
                //options.TokenCookie.Expiration = TimeSpan.Zero;
                options.AutoValidate = false; //表示不验证防伪令牌
            });

          

            //context.Services.AddHealthChecks();
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            app.UseCorrelationId();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseCors("CorsPolicy");
            app.UseCors(DefaultCorsPolicyName);
            // 添加认证中间件
            app.UseAuthentication();
            app.UseMultiTenancy();
            //添加授权中间件
            app.UseAuthorization();
           // app.UseJwtTokenMiddleware();
            app.UseAbpClaimsMap();
            //app.Use(async (ctx, next) =>
            //{
            //    var currentPrincipalAccessor = ctx.RequestServices.GetRequiredService<ICurrentPrincipalAccessor>();
            //    var map = new Dictionary<string, string>()
            //    {
            //        { "sub", AbpClaimTypes.UserId },
            //        { "role", AbpClaimTypes.Role },
            //        { "email", AbpClaimTypes.Email },
            //        { "name", AbpClaimTypes.UserName },
            //    };
            //    var mapClaims = currentPrincipalAccessor.Principal.Claims.Where(p => map.Keys.Contains(p.Type)).ToList();
            //    currentPrincipalAccessor.Principal.AddIdentity(new ClaimsIdentity(mapClaims.Select(p => new Claim(map[p.Type], p.Value, p.ValueType, p.Issuer))));
            //    await next();
            //});

            app.UseAbpRequestLocalization();
            //swagger页面访问授权
           // app.UseSwaggerAuthorized();
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkflowService API");
            });
            app.UseAuditing();
            app.UseAbpSerilogEnrichers();
            app.UseUnitOfWork();
            //app.UseConfiguredEndpoints();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
            // 开启健康检测
            //app.UseHealthChecks("/HealthCheck");

            //注入Http
            Bridge.Shared.Helper.HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
        }
    }
}
